#pragma once
#include <iostream>
#include <signal.h>
#include <unistd.h>
#include "Sock.hpp"
#include <functional>

class HttpServer
{
public:
    using func_t = std::function<void(int)>;

private:
    int _listensock;
    uint16_t _port;
    Sock _sock;
    func_t _func;

public:
    HttpServer(uint16_t port, func_t func)
        : _port(port), _func(func)
    {
        _listensock = _sock.Socket();
        _sock.Bind(_listensock, _port);
        _sock.Listen(_listensock);
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        for (;;)
        {
            std::string clientip;
            uint16_t clientport;
            int servicefd = _sock.Accept(_listensock, &clientip, &clientport);
            if (servicefd < 0)  continue;
            if(fork() == 0)
            {
                close(_listensock);
                _func(servicefd);
                close(servicefd);
                exit(0);
            }
            close(servicefd);
        }
    }
    ~HttpServer() 
    {
        if(_listensock >= 0) close(_listensock);
    }
};